package com.user.query.utils;

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class IPUtil {
	/**
	 * 根据ip获取地区信息  调用淘宝ip库
	 * @param ip
	 * @return
	 * @throws
	 */
public static String getIpArea(String ip){
		String path = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip;
		String inputline="";
		String info="";
		
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setReadTimeout(10*1000);
			conn.setRequestMethod("GET");
			
			InputStreamReader  inStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
			BufferedReader buffer=new BufferedReader(inStream);
			while((inputline=buffer.readLine())!=null){
				info+=inputline;
			}
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		JSONObject jsonob = JSONObject.fromObject((JSONObject.fromObject(info).getString("data")));
	    String city = StringEscapeUtils.escapeSql(jsonob.getString("city"));
	    String region = StringEscapeUtils.escapeSql(jsonob.getString("region"));
	    if(city.equals("")&&region.equals("")){
	    	return "未知地区";
	    }
	    return region+city;
	}

public String getIpAddr(HttpServletRequest request) {
	  String ip = request.getHeader("x-forwarded-for");
	  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	   ip = request.getHeader("Proxy-Client-IP");
	  }
	  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	   ip = request.getHeader("WL-Proxy-Client-IP");
	  }
	  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	   ip = request.getRemoteAddr();
	  }
	  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	   ip = request.getHeader("http_client_ip");
	  }
	  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	   ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	  }
	  // 如果是多级代理，那么取第一个ip为客户ip
	  if (ip != null && ip.indexOf(",") != -1) {
	   ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
	  }
	  return ip;
	 }
}
